Page({
  data: {
    bannerList: [
      {
        id: 1,
        imgUrl: '/assets/images/banner/banner1.jpg'
      },
      {
        id: 2,
        imgUrl: '/assets/images/banner/banner2.jpg'
      },
      {
        id: 3,
        imgUrl: '/assets/images/banner/banner3.jpg'
      }
    ],
    serviceCategories: [],
    recommendServices: [],
    loading: false,
    categoryPage: 1,
    pageSize: 5,
    servicePage: 1,
    hasMoreServices: true,
    bannersLoaded: false // 轮播图加载状态
  },

  onLoad() {
    this.ensureBannerImages()
    this.getCategoryList()
    this.getRecommendServices()
  },

  // 确保轮播图加载
  ensureBannerImages() {
    // 检查轮播图是否已加载
    if (this.data.bannersLoaded) {
      return
    }

    // 预加载轮播图图片，确保它们能正确显示
    const bannerList = this.data.bannerList
    let loadedCount = 0

    bannerList.forEach(banner => {
      wx.getImageInfo({
        src: banner.imgUrl,
        success: () => {
          loadedCount++
          if (loadedCount === bannerList.length) {
            this.setData({
              bannersLoaded: true
            })
          }
        },
        fail: () => {
          console.error('轮播图加载失败:', banner.imgUrl)
        }
      })
    })
  },

  // 获取分类列表
  getCategoryList() {
    const that = this
    this.setData({
      loading: true
    })

    // 引入请求工具
    const { post } = require('../../utils/request')

    post('/api/category/list/page/vo', {
      current: 1,
      pageSize: 5 // 首页只展示5个分类
    }).then(res => {
      const categoryList = res.data.records.map(item => {
        // 处理图片为空的情况，使用默认图片
        return {
          ...item,
          icon: item.image || '/assets/images/default.png'
        }
      })

      that.setData({
        serviceCategories: categoryList
      })
    }).catch(err => {
      console.error('获取分类列表失败', err)
      wx.showToast({
        title: '获取分类失败',
        icon: 'none'
      })
    }).finally(() => {
      that.setData({
        loading: false
      })
    })
  },

  // 获取推荐服务
  getRecommendServices() {
    const that = this
    const { post } = require('../../utils/request')

    this.setData({
      loading: true
    })

    post('/api/services/list/page/vo', {
      current: this.data.servicePage,
      pageSize: this.data.pageSize,
      sortField: 'createTime',
      sortOrder: 'desc'
    }).then(res => {
      const newServices = res.data.records.map(item => {
        return {
          id: item.id,
          title: item.name,
          desc: item.description || '暂无描述',
          price: item.price,
          unit: '次',
          imgUrl: item.image || '/assets/images/default.png'
        }
      })

      that.setData({
        recommendServices: this.data.servicePage === 1 ? newServices : [...this.data.recommendServices, ...newServices],
        hasMoreServices: res.data.current < res.data.pages
      })
    }).catch(err => {
      console.error('获取推荐服务失败', err)
      wx.showToast({
        title: '获取服务失败',
        icon: 'none'
      })
    }).finally(() => {
      that.setData({
        loading: false
      })

      // 服务加载完毕后，确保轮播图已加载
      this.ensureBannerImages()
    })
  },

  // 加载更多推荐服务
  loadMoreServices() {
    if (this.data.hasMoreServices && !this.data.loading) {
      this.setData({
        servicePage: this.data.servicePage + 1
      })
      this.getRecommendServices()
    }
  },

  // 跳转到服务详情
  goToServiceDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/service/detail/detail?id=${id}`
    })
  },

  // 跳转到服务分类页
  goToServiceCategory(e) {
    const id = e.currentTarget.dataset.id
    const name = e.currentTarget.dataset.name
    const index = e.currentTarget.dataset.index

    // 跳转到服务页面，并传递分类索引
    wx.switchTab({
      url: '/pages/service/service',
      success: () => {
        // 使用全局变量存储需要激活的分类ID，供服务页面使用
        getApp().globalData = getApp().globalData || {}
        getApp().globalData.activeCategoryId = id
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      servicePage: 1,
      bannersLoaded: false // 重置轮播图加载状态
    })
    this.ensureBannerImages()
    this.getCategoryList()
    this.getRecommendServices()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMoreServices()
  }
}) 